<!-- 图片详情页面 -->
<template>
	<!-- 页面布局 -->
	<view class="box-layout" v-if="browseImageIndexs.length">
		<!-- 图片布局 -->
		<view class="box-image" @click="onShow">
			<swiper circular :current="currentIndex" @change="onSlide">
				<swiper-item v-for="(item, index) in subjectDetails" :key="item._id">
					<image mode="aspectFill" :src="item.picurl" v-if="browseImageIndexs.includes(index)"></image>
				</swiper-item>
			</swiper>
		</view>
		<!-- 展示内容布局 -->
		<view class="box-show" v-show="isShow">
			<!-- 返回布局 -->
			<view class="box-show-back box-flex-center box-position-absolute-top-left"
				:style="{top: getMenuButtonBoundingClientRectMarginTop() + 'px', width: getMenuButtonBoundingClientRectHeight() + 'px', height: getMenuButtonBoundingClientRectHeight() + 'px'}"
				@click="onBack">
				<uni-icons type="left" size="30" color="rgb(255, 255, 255)"></uni-icons>
			</view>
			<!-- 页码布局 -->
			<view class="box-show-count box-position-absolute-top-left">{{currentIndex + 1}}/{{subjectDetails.length}}
			</view>
			<!-- 菜单布局 -->
			<view class="box-show-menu box-flex-space box-position-absolute-bottom-left">
				<!-- 信息菜单布局 -->
				<view class="box-show-menu-info" @click="onShowInfo">
					<uni-icons type="info" size="30"></uni-icons>
					<view>信息</view>
				</view>
				<!-- 评分菜单布局 -->
				<view @click="onShowScore">
					<uni-icons type="star" size="30"></uni-icons>
					<view>{{currentInfo.score}}分</view>
				</view>
				<!-- 下载菜单布局 -->
				<view class="box-show-menu-info" @click="onSaveImage">
					<uni-icons type="download" size="30"></uni-icons>
					<view>下载</view>
				</view>
			</view>
		</view>
		<!-- 信息弹窗 -->
		<uni-popup ref="infoPopup" type="bottom" :safe-area="false">
			<!-- 信息弹窗布局 -->
			<view class="box-info">
				<!-- 信息头部布局 -->
				<view class="box-flex-space">
					<view style="opacity: 0;">
						<uni-icons type="closeempty" size="30"></uni-icons>
					</view>
					<view>壁纸信息</view>
					<view @click="onCloseInfo">
						<uni-icons type="closeempty" size="30"></uni-icons>
					</view>
				</view>
				<!-- 信息内容布局 -->
				<view class="box-info-content">
					<scroll-view scroll-y>
						<!-- 壁纸ID布局 -->
						<view class="box-info-content-item">
							<view class="">壁纸ID：</view>
							<text class="box-info-content-item-value" selectable>{{currentInfo._id}}</text>
						</view>
						<!-- 发布者布局 -->
						<view class="box-info-content-item">
							<view class="">发布者：</view>
							<view class="box-info-content-item-value">{{currentInfo.nickname}}</view>
						</view>
						<!-- 评分布局 -->
						<view class="box-info-content-item">
							<view class="">评分：</view>
							<view class="box-info-content-item-value box-info-content-item-score box-flex-center-y">
								<uni-rate readonly :value="currentInfo.score"></uni-rate>
								<view class="box-info-content-item-score-text">{{currentInfo.score}}分</view>
							</view>
						</view>
						<!-- 摘要布局 -->
						<view class="box-info-content-item">
							<view class="">摘要：</view>
							<text class="box-info-content-item-value">{{currentInfo.description}}</text>
						</view>
						<!-- 标签布局 -->
						<view class="box-info-content-item">
							<view class="">标签：</view>
							<view class="box-info-content-item-value box-info-content-item-label">
								<view class="box-info-content-item-label-item" v-for="(item, index) in currentInfo.tabs"
									:key="index">{{item}}
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</uni-popup>
		<!-- 评分弹窗 -->
		<uni-popup ref="scorePopup" :is-mask-click="false">
			<!-- 评分布局 -->
			<view class="box-score">
				<!-- 评分头部布局 -->
				<view class="box-flex-space">
					<view style="opacity: 0;">
						<uni-icons type="closeempty" size="30"></uni-icons>
					</view>
					<view class="">{{isScore ? '已评分' : '未评分'}}</view>
					<view class="" @click="onCloseScore">
						<uni-icons type="closeempty" size="30"></uni-icons>
					</view>
				</view>
				<!-- 评分分数布局 -->
				<view class="box-score-content box-flex-center">
					<uni-rate allowHalf :disabled="isScore" disabled-color="rgb(255, 202, 62)"
						v-model="userScore"></uni-rate>
					<view>{{userScore}}分</view>
				</view>
				<!-- 评分菜单布局 -->
				<view class="box-flex-center">
					<button type="default" size="mini" plain :disabled="!userScore || isScore"
						@click="onSubmitScore">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
	//导入
	import { ref } from "vue";
	import { onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
	import { getMenuButtonBoundingClientRectMarginTop, getMenuButtonBoundingClientRectHeight } from "@/utils/system.ts";
	import { navigateBack, reLaunch, showToast, showLoading, showModal, getImageInfo, saveImageToPhotosAlbum, openSetting } from "@/utils/uni-api.ts";
	import { url_recommend, url_image_detail } from "@/utils/url.ts";
	import { api_submitScore, api_submitDownloadLog, api_getWallpaperDetail } from "@/api/api.ts";

	//参数
	let subjectDetails = ref([]);
	let currentIndex = ref(0);
	let currentInfo = ref({ _id: "", nickname: "", score: 0, userScore: null, description: "", tabs: [], classid: "", picurl: "" });
	//浏览图片索引集合
	let browseImageIndexs = ref([]);
	let isShow = ref(true);
	let infoPopup = ref(null);
	let scorePopup = ref(null);
	let userScore = ref(0);
	let isScore = ref(false);

	//初始化执行方法
	getSubjectDetails();

	//内部事件
	//获取专题详情
	function getSubjectDetails() {
		let storageSubjectDetails = uni.getStorageSync("subjectDetails") || [];
		subjectDetails.value = storageSubjectDetails.map((item : any) => {
			return { ...item, picurl: item.smallPicurl.replace('_small.webp', '.jpg') };
		});
	};
	//修改浏览图片索引集合
	function updateBrowseImageIndexs() {
		//加载当前图片，上一张图片，下一张图片
		browseImageIndexs.value.push(
			currentIndex.value <= 0 ? subjectDetails.value.length - 1 : currentIndex.value - 1,
			currentIndex.value,
			currentIndex.value >= subjectDetails.value.length - 1 ? 0 : currentIndex.value + 1
		);
		//去重
		browseImageIndexs.value = [...new Set(browseImageIndexs.value)];
	};
	//滑动图片
	function onSlide(e : any) {
		currentIndex.value = e.detail.current;
		currentInfo.value = subjectDetails.value[currentIndex.value];
		updateBrowseImageIndexs();
	};
	//点击修改显示
	function onShow() {
		isShow.value = !isShow.value;
	};
	//点击返回
	function onBack() {
		navigateBack({ fail: () => reLaunch({ url: url_recommend }) });
	};
	//展示信息
	function onShowInfo() {
		infoPopup.value.open();
	};
	//关闭展示信息
	function onCloseInfo() {
		infoPopup.value.close();
	};
	//展示评分
	function onShowScore() {
		if (currentInfo.value.userScore) {
			isScore.value = true;
			userScore.value = currentInfo.value.userScore;
		};
		scorePopup.value.open();
	};
	//关闭展示评分
	function onCloseScore() {
		scorePopup.value.close();
		isScore.value = false;
		userScore.value = 0;
	};
	//提交评分
	function onSubmitScore() {
		submitScore().finally(() => {
			onCloseScore();
		});
	};
	//保存图片
	function onSaveImage() {
		//H5是提示，非H5是保存图片
		// #ifdef H5
		showModal({ title: "请长按保存壁纸", showCancel: false });
		// #endif
		// #ifndef H5
		showLoading({ title: "下载中...", mask: true });
		//提交下载日志
		submitDownloadLog().then(() => {
			//下载图片
			getImageInfo({
				src: currentInfo.value.picurl,
				success: (res : any) => {
					//保存图片
					saveImageToPhotosAlbum({
						filePath: res.path,
						success: () => {
							showToast({ title: "保存成功" });
						},
						fail: (err : any) => {
							if (err.errMsg == "saveImageToPhotosAlbum:fail cancel") {
								showToast({ title: "保存失败" });
								return;
							}
							showModal({
								title: "提示", content: "需要授权保存相册",
								success: (res : any) => {
									if (res.confirm) {
										//打开授权
										openSetting({
											success: (res : any) => {
												if (res.authSetting['scope.writePhotosAlbum']) {
													showToast({ title: "获取授权成功" });
												} else {
													showToast({ title: "获取授权失败" });
												};
											}
										});
									};
								}
							});
						}
					});
				},
				complete: () => {
					uni.hideLoading();
				}
			});
		}).finally(() => {
			uni.hideLoading();
		});
		// #endif
	};
	//初始化部分参数
	function init() {
		currentIndex.value = subjectDetails.value.findIndex(item => item._id == currentInfo.value._id);
		currentInfo.value = subjectDetails.value[currentIndex.value];
		updateBrowseImageIndexs();
	};

	//页面生命周期
	//页面加载
	onLoad((e) => {
		let { id: eId = "", type: eType = "" } = e;
		currentInfo.value._id = eId;
		if (eType == "share") {
			getWallpaperDetail().then(() => {
				init();
			});
		};
		init();
	});
	//分享到微信
	onShareAppMessage(() => {
		return {
			title: "壁纸",
			path: url_image_detail + "?id=" + currentInfo.value._id + "&type=share"
		};
	});
	//分享到朋友圈
	onShareTimeline(() => {
		return {
			title: "壁纸",
			query: "id=" + currentInfo.value._id + "&type=share"
		};
	});

	//网络请求
	//提交评分
	async function submitScore() {
		showLoading({ title: "请求中..." });
		let { classid, _id: wallId } = currentInfo.value;
		let res : any = await api_submitScore({
			classid,
			wallId,
			userScore: userScore.value
		});
		uni.hideLoading();
		if (res.errCode === 0) {
			subjectDetails.value[currentIndex.value].userScore = userScore.value;
			uni.setStorageSync("subjectDetails", subjectDetails.value);
			showToast({ title: "评分成功" });
		};
	};
	//提交下载日志
	async function submitDownloadLog() {
		let { classid, _id: wallId } = currentInfo.value;
		return await api_submitDownloadLog({
			classid,
			wallId
		});
	};
	//获取壁纸详情
	async function getWallpaperDetail() {
		let res : any = await api_getWallpaperDetail({ id: currentInfo.value._id });
		subjectDetails.value = res.data.map((item : any) => {
			return {
				...item,
				picurl: item.smallPicurl.replace('_small.webp', '.jpg')
			};
		});
	};
</script>

<style lang="scss" scoped>
	@import "../../common/css/common.css";

	.box-layout {
		width: 100vw;
		height: 100vh;

		.box-image {
			width: 100%;
			height: 100%;

			swiper {
				width: 100%;
				height: 100%;

				swiper-item {
					width: 100%;
					height: 100%;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}
		}

		.box-show {
			.box-show-back {
				left: 20rpx;
				color: $custom-color-white;
				background: $custom-rgba-2;
				border-radius: 50%;
				backdrop-filter: blur(5rpx);
			}

			.box-show-count {
				width: fit-content;
				top: 10vh;
				right: 0;
				margin: auto;
				color: $custom-color-white;
				background: $custom-rgba-2;
				border-radius: 30rpx;
				padding: 10rpx 30rpx;
				backdrop-filter: blur(5rpx);
			}

			.box-show-menu {
				width: 50vw;
				bottom: 10vh;
				right: 0;
				margin: auto;
				background: $custom-color-white;
				border-radius: 30rpx;

				.box-show-menu-info {
					margin: 0 20rpx;
				}
			}
		}

		.box-info {
			background: $custom-color-white;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;

			.box-info-content {
				scroll-view {
					max-height: 60vh;

					.box-info-content-item {
						display: flex;
						padding: 30rpx 0;

						.box-info-content-item-value {
							flex: 1;
						}

						.box-info-content-item-score {
							.box-info-content-item-score-text {
								padding-left: 10rpx;
							}
						}

						.box-info-content-item-label {
							display: flex;
							flex-wrap: wrap;

							.box-info-content-item-label-item {
								border: 1px solid $custom-color-green;
								padding: 10rpx 20rpx;
								border-radius: 50rpx;
								margin: 0 10rpx 10rpx;
								line-height: 1em;
							}
						}
					}
				}
			}
		}

		.box-score {
			width: 60vw;
			background: $custom-color-white;
			padding: 30rpx;
			border-radius: 30rpx;

			.box-score-content {
				padding: 30rpx 0;
			}
		}
	}
</style>